#======================================================================
# Product:      KnowledgeEngine (Plone Version)
#
# File:         B2Evolution.py
#
# Copyright:    Copyright (c) 2006, Faulkner Technologies
#
# Author:       John Meredith
#
# Description:  B2Evolution client
#======================================================================


#======================================================================
# KnowledgeEngine Imports
#----------------------------------------------------------------------
from BloggerAPI import *

#======================================================================
# Zope Library Imports
#----------------------------------------------------------------------


#======================================================================
# Python Library Imports
#----------------------------------------------------------------------
import os
import sys
import unittest


#======================================================================
# Class definition
#----------------------------------------------------------------------
class B2Evolution(BloggerAPI):
    """
        The B2Evolution blog conforms largely to the BloggerAPI except
        that it won't accept a post without a category. As the
        BloggerAPI does not have the option to specify one, we need
        a new client :-/
    """


    # Some meta-data for the blog client
    TITLE = "B2Evolution"


    def getCategories(self):
        """
            Return a list of available categories
        """
        
        server = self.getServer()

        return server.b2.getCategories(str(self.args['blogId']), self.username, self.password)
        

    def createPost(self, **args):
        """
            Create a new post. 
        """

        # Setup default newPost parameters
        config = {
            'title'     : 'A title',
            'publish'   : True
        }
        config.update(args)

        # Check that we have some content
        if not config.has_key('content') or not config['content']:
            raise TypeError, "A blog post must contain some form of content/body text."

        content = config['content']
        
        # Check B2Evolutions requirement for a category when creating a new post.
        if not config.has_key('category') or not config['category'] :
            raise TypeError, "You must specify a category when creating a new post on B2Evolution"

        #----------------------------------------------------------------------
        # Use the B2 API newPost instead of the BloggerAPI one as it allows for
        # the inclusion of a category.
        #
        # NOTE: b2.newPost() has a wierd-arsed parameter specification. The
        #       first two params are not used at all, plus the 'publish'
        #       boolean is ignored completely.
        #----------------------------------------------------------------------
        server = self.getServer()
        postId = server.b2.newPost(
            '',                                     # Unknown/unused!!!
            '',                                     # Unknown/unused!!!
            self.username,                          # Username
            self.password,                          # Password
            content,                                # Post content
            bool(config.get('publish', True)),      # Ignored!!!
            config.get('title', 'Title placeholder'),   # Title
            config['category'],                     # Categories
            config.get('postDate', ''),             # Pass through a date if available
        )
        
        return postId


#======================================================================
# Register Blog client with the action
#----------------------------------------------------------------------
from Products.KnowledgeEngine.Actions.BlogPost.Clients import registerBlogClient
registerBlogClient(B2Evolution)


#======================================================================
# Unit Tests
#----------------------------------------------------------------------
class B2EvolutionTests(unittest.TestCase):
    def setUp(self):
        self.client = B2Evolution('johnm', 'Lmmsoht', 'http://127.0.0.1/b2evolution/blogs/xmlsrv/xmlrpc.php', blogId=5)


    def testConnection(self):
        """
            Test that the connection is valid. Requires a blog :-)
        """

        # Check B2Evolution
        self.failUnless(self.client.isValidConnection())


    def testPosting(self):
        """
            Test that we can create a new post
        """

        newPost = {
            'content' : "New post content",
            'category' : 18
        }

        # Create a post
        postId = self.client.createPost(**newPost)
        self.failUnless(postId)

        # Edit the post
        self.failUnless(self.client.editPost(postId, content="This has been edited", publish=True))

        # Grab our post by Id and check that it's been edited
        post = self.client.getPost(postId)
        self.failUnless(post)
        self.failUnless(post['content'] == "This has been edited")

        # Try to delete out post
        self.failUnless(self.client.deletePost(postId))


if __name__ == '__main__':
    unittest.main()
